package BQ;

public class MyBlockingQueue {
    private final String[] data;
    private int head = 0;
    private int last = 0;
    private int size = 0;

    public MyBlockingQueue(int capacity) {
        if(capacity <= 0) {
            throw new IllegalArgumentException("参数值超出合理范围");
        }
        data = new String[capacity];
    }

    synchronized public void put(String elem) throws InterruptedException {
            while (size == data.length) {
                //队列满了,进行阻塞，当队列不满时唤醒
                this.wait();
            }
            data[last] = elem;
            last++;
            if (last == data.length) {
                last = 0;
            }
            size++;
            this.notify();
    }
    public String take() throws InterruptedException {
        synchronized (this){
            while (size == 0) {
                //队列为空，进行阻塞，当队列不为空时唤醒
                this.wait();
            }
            String ret = data[head];
            head++;
            if (head == data.length) {
                head = 0;
            }
            size--;
            this.notify();
            return ret;
        }
    }
}
class MyTest {
    public static void main(String[] args) {
        MyBlockingQueue myBlockingQueue = new MyBlockingQueue(10);
        Thread thread1 = new Thread(() -> {
            int num = 0;
            while (true){
                try {
                    myBlockingQueue.put(num+"");
                    System.out.println("生产了："+num);
                    num++;
                    //Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        Thread thread2 = new Thread(() -> {
            while (true){
                try {
                    String s = myBlockingQueue.take();
                    System.out.println("消费了："+s);
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        thread1.start();
        thread2.start();
     }
}